﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace _7zipWrapper
{
    /// <summary>
    ///   Interaction logic for ExtensionsWindow.xaml
    /// </summary>
    public partial class ExtensionsWindow
    {
        readonly List<string> extensions;

        public ExtensionsWindow()
        {
            InitializeComponent();
        }

        public ExtensionsWindow(List<string> extensions)
            : this()
        {
            this.extensions = extensions;
        }

        void Window_Loaded(object sender, RoutedEventArgs e)
        {
            PopulateGridWithExtensions();
        }

        /// <summary>
        /// Read the extensions from file and populate the grid.
        /// </summary>
        void PopulateGridWithExtensions()
        {
            string defaultExntensions;
            using (StreamReader sr = new StreamReader("Files\\DefaultExtensions.txt"))
            {
                defaultExntensions = sr.ReadToEnd();
            }

            string[] defaultExtensionsArray = defaultExntensions.Split(',');
            List<string> defaultExtensionsList =
                defaultExtensionsArray.Where(k => !string.IsNullOrEmpty(k)).Select(s => s.TrimStart('.').Trim()).ToList();

            // we know that we have 10 columns, so here add enough rows to hold all extensions
            int extensionsRowCount = Convert.ToInt32(Math.Ceiling((decimal) defaultExtensionsList.Count / 10));
            for (int i = 0; i < extensionsRowCount; i++)
            {
                RowDefinition newRowDefinition = new RowDefinition {Height = new GridLength(25)};
                extensionsGrid.RowDefinitions.Add(newRowDefinition);
            }

            int rowCounter = 0;
            int itemsPerColumn = extensionsGrid.RowDefinitions.Count();

            foreach (string extension in defaultExtensionsList)
                // we start the name with _ cause some extensions start with a number and this is not a valid name for a control
            {
                int column = rowCounter / itemsPerColumn;
                int row = rowCounter % itemsPerColumn;

                CheckBox checkBox = new CheckBox
                    {
                        IsChecked = false,
                        Name = "_" + extension.Replace(".", "_") + "CheckBox",
                        Content = extension,
                        Margin = new Thickness(4)
                    };

                extensionsGrid.Children.Add(checkBox);
                Grid.SetColumn(checkBox, column);
                Grid.SetRow(checkBox, row);
                rowCounter++;
            }

            // populate the checkboxes according to the existing extensions, if any 
            foreach (CheckBox element in extensionsGrid.Children.OfType<CheckBox>())
            {
                element.IsChecked = extensions.Contains(element.Content);
            }

            // add any new items as checkboxes if they don't already exist in the list 
            foreach (string extension in extensions)
            {
                bool exists =
                    extensionsGrid.Children.OfType<CheckBox>().Any(element => element.Content.Equals(extension));

                if (exists)
                    continue;
                CheckBox checkBox = new CheckBox
                    {
                        IsChecked = true,
                        Name = "_" + extension.Replace(".", "_") + "CheckBox",
                        Content = extension,
                        Margin = new Thickness(4)
                    };
                extensionsGrid.Children.Add(checkBox);
            }
        }

        void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        void okButton_Click(object sender, RoutedEventArgs e)
        {
            // populate the extensions list 
            extensions.Clear();

            foreach (CheckBox element in extensionsGrid.Children.OfType<CheckBox>().Where(element => element.IsChecked.HasValue && element.IsChecked.Value && !extensions.Contains(element.Content)))
            {
                extensions.Add(element.Content.ToString());
            }

            DialogResult = true;
            Application.Current.Properties["extenstionsList"] = extensions;
            Close();
        }

        void allButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (CheckBox element in extensionsGrid.Children.OfType<CheckBox>())
            {
                element.IsChecked = true;
            }
        }

        void noneButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (CheckBox element in extensionsGrid.Children.OfType<CheckBox>())
            {
                element.IsChecked = false;
            }
        }
    }
}